import axios from 'axios'
import { Toast } from 'vant'
import { getToken } from '@/utils/index'

const { VITE_BASE_URL } = import.meta.env

const service = axios.create({
  baseURL: VITE_BASE_URL,
  timeout: 5000,
  headers: {
    token: getToken(),
  },
})

service.interceptors.request.use(
  (config) => {
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '请稍等~',
    })
    return config
  },
  (error) => {
    console.error(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const { data: res } = response
    Toast.clear()

    if (res?.code !== 200) {
      Toast.fail(res?.message || '请求失败！')
      return Promise.reject(res)
    }
    return Promise.resolve(res)
  },
  (error) => {
    console.error(error)
    Toast.clear()
  }
)

function request2Get(config) {
  return service({
    ...config,
    method: 'get',
  })
}

function request2Post(config) {
  return service({
    ...config,
    method: 'post',
  })
}

export { request2Get, request2Post }
